package edu.ccut.titan.tag.chart.render;

import java.awt.Font;
import java.text.NumberFormat;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.data.general.DefaultPieDataset;

import edu.ccut.titan.tag.chart.utils.ChartInfo;

/**
 * 饼状图渲染
 * @author LeslieGu
 *
 */
public class PieChartRender extends ChartRender{
	
	private DefaultPieDataset getPieDatasetDataset(List<List<?>> datas) {
		DefaultPieDataset pieDataset = new DefaultPieDataset();

		if (datas != null) {
			for (List<?> data : datas) {
				if (data.size() > 1) {
					try {
						pieDataset.setValue((Comparable<?>) data.get(0),
								(Number) data.get(1));
					} catch (RuntimeException e) {
						e.printStackTrace();
					}
				}
			}
		}

		return pieDataset;
	}
	
	@Override
	protected JFreeChart createChart(ChartInfo chartInfo) {
		JFreeChart chart = ChartFactory.createPieChart(chartInfo.getTitle(),
                this.getPieDatasetDataset(chartInfo.getDatas()), chartInfo.isLegend(),
                chartInfo.isTooltips(), chartInfo.isUrls());
		return chart;
	}
	
    protected Plot renderPrivateChart(JFreeChart chart, ChartInfo chartInfo) {
//        PiePlot3D pieplot = (PiePlot3D) chartInfo.getChart().getPlot();
        PiePlot pieplot = (PiePlot) chart.getPlot();
        pieplot.setLabelFont(new Font("SansSerif", 0, 12));
        pieplot.setForegroundAlpha(0.5f);
        //显示百分比
        //先设置百分比的显示精度ȵ���ʾ����
        NumberFormat lableFormat = NumberFormat.getPercentInstance();
        lableFormat.setMaximumFractionDigits(2);
        //在StandardPieItemLabelGenerator中的"{n}={n}" 表示："key=value"
        //n：0—Key 1—value 2—％ 3－100
        pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} 占 {2}", lableFormat, lableFormat));
        pieplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
        pieplot.setToolTipGenerator(new StandardPieToolTipGenerator("{0} 值为 {1}"));

        pieplot.setCircular(true);
        pieplot.setLabelGap(0.02D);
        return pieplot;
    }
}
